﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Preyla
{
    public partial class FormConfigurations : Form
    {
        int Rights;

        IDatabase DBManager = new AccessManager(Properties.Settings.Default.ConnectionString);

        List<int> DeletedConfigurations = new List<int>();

        int ServerID;

        int ConfigurationID = 0;

        Color DefaultColor;
        Color AlternatingDefaultColor;

        public FormConfigurations(int ServerID, string ServerName, int Rights)
        {
            InitializeComponent();

            this.ServerID = ServerID;
            this.Text = ServerName + " configurations";

            this.Rights = Rights;
        }

        public int GetConfigurationID
        { 
            get { return ConfigurationID; }
        }

        private void ConfigurationsTable_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2 && e.RowIndex != -1 && e.RowIndex != ConfigurationsTable.Rows.Count-1)
            {
                bool b = Save();

                if (!b)
                {
                    return;
                }

                FormSystem formServer = new FormSystem(ServerID, Int32.Parse(ConfigurationsTable[0, e.RowIndex].Value.ToString()), ConfigurationsTable[1, e.RowIndex].Value.ToString(), Rights);

                formServer.ShowDialog();
            }
        }

        private void CloseButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void FormConfigurations_Load(object sender, EventArgs e)
        {
            DBManager.Open();

            DefaultColor = ConfigurationsTable.DefaultCellStyle.BackColor;
            AlternatingDefaultColor = ConfigurationsTable.AlternatingRowsDefaultCellStyle.BackColor;

            Read();

            if (Rights == 2)
            {
                //ConfigurationsTable.AllowUserToAddRows = false;
                ConfigurationsTable.AllowUserToDeleteRows = false;
                ConfigurationsTable.ReadOnly = true;
            }
        }

        void Read()
        {
            string[][] Data = DBManager.ExecuteReader("SELECT Configurations.ID, Configurations.[Name] FROM Objects Configurations, Objects Servers, Links WHERE Duplication = 0 AND Links.ID = Servers.ID AND Links.ObjectID = Configurations.ID AND Servers.ID = " + ServerID + ";");

            for (int i = 0; i < Data.Length; i++)
            {
                ConfigurationsTable.Rows.Add();
                ConfigurationsTable[0, ConfigurationsTable.Rows.Count - 2].Value = Data[i][0];
                ConfigurationsTable[1, ConfigurationsTable.Rows.Count - 2].Value = Data[i][1];
                ConfigurationsTable[2, ConfigurationsTable.Rows.Count - 2].Value = "Edit...";
            }
        }

        bool Save()
        {
            for (int i = 0; i < ConfigurationsTable.Rows.Count - 1; i++)
            {
                try
                {
                    if (ConfigurationsTable[1, i].Value == null)
                    {
                        MessageBox.Show("Configuration name is empty");

                        return false;
                    }

                    string Name = ConfigurationsTable[1, i].Value.ToString().Trim();

                    if (Name == "")
                    {
                        MessageBox.Show("Configuration name is empty");

                        return false;
                    }

                    for (int j = 0; j < ConfigurationsTable.Rows.Count - 1; j++)
                    {
                        if (i == j) continue;
                        if (Name.CompareTo(ConfigurationsTable[1, j].Value.ToString()) == 0)
                        {
                            MessageBox.Show("Configuration name " + Name + " is used twice");

                            return false;
                        }
                    }

                    if (ConfigurationsTable[0, i].Value != null)
                    {
                        DBManager.ExecuteNonQuery(String.Format("UPDATE Objects SET [Name]='{1}' WHERE ID = {0};", ConfigurationsTable[0, i].Value, ConfigurationsTable[1, i].Value));
                    }
                    else
                    {
                        DBManager.ExecuteNonQuery(String.Format("INSERT INTO Objects ([Name]) VALUES ('{0}')", ConfigurationsTable[1, i].Value));

                        int ID = DBManager.ExecuteScalar("SELECT @@IDENTITY;");

                        ConfigurationsTable[0, i].Value = ID;

                        //DBManager.ExecuteNonQuery("INSERT INTO Objects (Name) VALUES ('New configuration')");

                        DBManager.ExecuteNonQuery("INSERT INTO Links (ID, ObjectID, Duplication) VALUES (" + ID + ", NULL, NULL)");
                        DBManager.ExecuteNonQuery("INSERT INTO Links (ID, ObjectID, Duplication) VALUES (" + ServerID + ", " + ID + ", 0)");
                    }
                }
                catch (Exception ex)
                { }
            }

            for (int i = 0; i < DeletedConfigurations.Count; i++)
            {
                DBManager.ExecuteNonQuery("DELETE FROM Objects WHERE ID = " + DeletedConfigurations[i]);

                DBManager.ExecuteNonQuery("DELETE FROM Links WHERE ID = " + DeletedConfigurations[i] + " OR ObjectID = " + DeletedConfigurations[i]);
            }

            DeletedConfigurations.Clear();

            return true;
        }

        private void FormConfigurations_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool b = Save();

            if (!b)
            {
                DialogResult dialogResult = MessageBox.Show("There are errors during saving. Quit without saving?", "Warning", MessageBoxButtons.YesNo);

                if (dialogResult == DialogResult.Yes)
                {
                    DBManager.Close();
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void ConfigurationsTable_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Delete row?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    DeletedConfigurations.Add(Int32.Parse(ConfigurationsTable[0, e.Row.Index].Value.ToString()));
                }
                else
                {
                    e.Cancel = true;
                }                
            }
            catch (Exception ex)
            { } 
        }

        private void AnalyzeButton_Click(object sender, EventArgs e)
        {
            if (!Save())
            {
                return;
            }

            if (ConfigurationsTable.SelectedRows.Count == 0)
            {
                MessageBox.Show("Select configuration");

                return;
            }

            int rowindex = ConfigurationsTable.SelectedRows[0].Index;

            ConfigurationID = Int32.Parse(ConfigurationsTable[0, rowindex].Value.ToString());

            Close();
        }

        private void ConfigurationsTable_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            ConfigurationsTable[2, ConfigurationsTable.Rows.Count - 2].Value = "Edit...";
        }

        private void SearchText_TextChanged(object sender, EventArgs e)
        {
            Search(ConfigurationsTable, SearchText.Text);
        }

        void Search(DataGridView datagrid, string Search)
        {
            for (int i = 0; i < datagrid.Rows.Count - 1; i++)
            {
                if (i % 2 == 0)
                {
                    for (int j = 1; j < datagrid.Columns.Count; j++)
                    {
                        datagrid[j, i].Style.BackColor = DefaultColor;
                    }
                }
                else
                {
                    for (int j = 1; j < datagrid.Columns.Count; j++)
                    {
                        datagrid[j, i].Style.BackColor = AlternatingDefaultColor;
                    }
                }
            }

            if (SearchText.Text != "")
            {
                for (int i = 0; i < datagrid.Rows.Count - 1; i++)
                {
                    for (int j = 1; j < datagrid.Columns.Count; j++)
                    {
                        if (datagrid[j, i].Value.ToString().Contains(Search))
                        {
                            for (int k = 1; k < datagrid.Columns.Count; k++)
                            {
                                datagrid[k, i].Style.BackColor = Color.FromArgb(180, 255, 180);
                            }
                        }
                    }
                }
            }
        }
    }
}
